package com.sitech.ibnms.c3p.task.notice;

import com.sitech.ibnms.c3p.domain.*;
import com.sitech.ibnms.c3p.mappers.C3pIspReportMapper;
import com.sitech.ibnms.c3p.mappers.NoticeMessageMapper;
import com.sitech.ibnms.c3p.mappers.TbSubscribeMailContentMapper;
import com.sitech.ibnms.c3p.mappers.TbSubscribeMailMapper;
import com.sitech.ibnms.c3p.util.C3pConstants;
import com.sitech.ibnms.c3p.util.JSONUtil;
import com.sitech.ibnms.c3p.util.SysDictUtil;
import com.sitech.ismp.workflow.domain.ProcessInstance;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.markdown4j.Markdown4jProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * Created by liujhc on 11/4.
 */
@Component
public class NoticeService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private C3pIspReportMapper ispReportMapper;
    @Autowired
    private TbSubscribeMailMapper mailMapper;
    @Autowired
    private TbSubscribeMailContentMapper mailContentMapper;
    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private NoticeMessageMapper noticeMessageMapper;
    private String messagePrefix;

    public void sendMessage(String addr,int execId,String messageContent){
        TbSubscribeMessage tbSubscribeMessage = new TbSubscribeMessage(addr, execId + UUID.randomUUID().toString().substring(8), getMessagePrefix()+messageContent);
        jmsTemplate.convertAndSend(C3pConstants.APPSERVER_SMS_QUEUE, JSONUtil.toJSON(tbSubscribeMessage));
        if(tbSubscribeMessage.getMESSAGE_CONTENT().length()>380){
            tbSubscribeMessage.setMESSAGE_CONTENT(tbSubscribeMessage.getMESSAGE_CONTENT().substring(0, 380) + "...");
        }
        noticeMessageMapper.insertMessage(new NoticeMessage(tbSubscribeMessage));
    }

    public void sendMessage(String[] addrList, int execId, String messageContent){
        for (String addr : addrList) {
            sendMessage(addr,execId,messageContent);
        }
    }

    public void sendMail(TbSubscribeMail mail, List<String> contents) {
        if (mail.getMESSAGE().length() > 250) {
            mail.setMESSAGE(mail.getMESSAGE().substring(0, 240) + "...");
        }
        mailMapper.insert(mail);
        mail.setTitle(getMessagePrefix() + mail.getMESSAGE());
        if (null != contents && !contents.isEmpty()) {
            StringBuffer sb = new StringBuffer();
            int size = contents.size();
            List<TbSubscribeMailContent> mailContents = new ArrayList<TbSubscribeMailContent>(size);
            for (int i = 0; i < size; i++) {
                sb.append(contents.get(i)).append("<br>");
                mailContents.add(new TbSubscribeMailContent(mail.getSERVIAL_ID(), i, contents.get(i)));
            }
            mailContentMapper.insert(mailContents);
            mail.setMESSAGE(sb.toString());
        }
        jmsTemplate.convertAndSend(C3pConstants.APPSERVER_MAIL_QUEUE, JSONUtil.toJSON(mail));
    }

    private String getMessagePrefix(){
        if(messagePrefix==null){
            SysDict sysDict = SysDictUtil.getSysDict(C3pConstants.SYSTEM_PARAM_DICT);
            if(sysDict==null||sysDict.getItems().size()==0||sysDict.getItemName(C3pConstants.C3P_APP_NAME_DICT_VALUE)==null){
                messagePrefix="";
            }else {
                String c3pAppName = sysDict.getItemName(C3pConstants.C3P_APP_NAME_DICT_VALUE);
                messagePrefix="【"+c3pAppName+"】";
            }
        }
        return messagePrefix;
    }

    public String getCompleteMail(String c3pTaskId, ProcessInstance processInstance, String noticeId) throws IOException {
        String mailContent = new Markdown4jProcessor().process(getTemplate(c3pTaskId, processInstance, noticeId));
        return "<style>\n" + ISP_REPORT_STYLE + "</style>\n" + "<div id='content'>" + mailContent + "</div>";
    }

    private String getTemplate(String c3pTaskId, ProcessInstance processInstance, String noticeId) {
        StringBuilder template = new StringBuilder();
        List<String> lines;
        lines = ispReportMapper.selectReportTemplate(c3pTaskId, noticeId);
        if (lines.isEmpty()) {
            lines = ispReportMapper.selectReportTemplate("default", null);
        }
        String createTime = DateFormatUtils.format(processInstance.getCreateTime(), "yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < lines.size(); i++) {
            String line = lines.get(i);
            try {
                if (line == null) line = "";
                //替换autoSitime, autoSitable
                line = line.replaceAll("<autoSitime>", createTime)
                        .replaceAll("<autoSitable>", processSiTable(processInstance));
                //替换sitable
                if (line.contains("<sitable ")) {
                    //转成json
                    String conf = "{" + line.substring(9, line.length() - 2) + "}";
                    conf = conf.replaceAll("=", ":")
                            .replaceAll("KPI_ID", ",KPI_ID")
                            .replaceAll("translate", ",translate");
                    line = processSiTable(processInstance, JSONUtil.fromJSON(conf, Map.class));
                }
            } catch (Exception e) {
                logger.warn(String.format("Mail content parse error at line %s: ", i + 1), e);
            }
            template.append(line).append('\n');
        }
        return template.toString();
    }

    private String processSiTable(ProcessInstance processInstance) {
        return processSiTable(processInstance, null);
    }

    private String processSiTable(ProcessInstance processInstance, Map confMap) {
        List<String> columns = Arrays.asList("UNIT_ID", "KPI_ID", "KPI_NAME", "KPI_VALUE", "COMPARE_RST", "CREATE_TIME");
        //生成表头
        StringBuilder siTable = new StringBuilder("<table class='imagetable'><tbody>");
        confMap = ObjectUtils.defaultIfNull(confMap, new HashMap());

        //表头文字翻译
        Map<String, String> translate = (Map<String, String>) confMap.get("translate");
        if (translate == null) {
            translate = new HashMap<String, String>();
            translate.put("CREATE_TIME", "执行时间");
            translate.put("KPI_ID", "指标代码");
            translate.put("KPI_VALUE", "指标值");
            translate.put("COMPARE_RST", "巡检结果");
            translate.put("UNIT_ID", "资源");
        }
        if (!translate.isEmpty()) {
            siTable.append("<tr>");
            for (String columnName : columns) {
                siTable.append("<th>")
                        .append(StringUtils.defaultString(translate.get(columnName), columnName))
                        .append("</th>");
            }
            siTable.append("</tr>");
        }

        //获取内容数据
        String[] unitIds = StringUtils.split(StringUtils.trim((String) confMap.get("UNIT_ID")), ',');
        String[] kpiIds = StringUtils.split(StringUtils.trim((String) confMap.get("KPI_ID")), ',');
        List<Map> rows = ispReportMapper.selectIspResult(unitIds, kpiIds, processInstance.getSerialNo());
        if (!rows.isEmpty()) {
            for (Map row : rows) {
                siTable.append("<tr>");
                for (String columnName : columns) {
                    siTable.append("<td>")
                            .append(ObjectUtils.defaultIfNull(row.get(columnName), ""))
                            .append("</td>");
                }
                siTable.append("</tr>");
            }
        }
        return siTable.append("</tbody></table>").toString();
    }


    private static final String ISP_REPORT_STYLE = "\n" +
            "html #content {\n" +
            "        font-size: 100%;\n" +
            "        -webkit-text-size-adjust: 100%;\n" +
            "        -ms-text-size-adjust: 100%;\n" +
            "    }\n" +
            "\n" +
            "    div#content {\n" +
            "        color: #444;\n" +
            "        font-family: 'Microsoft JhengHei', 'Microsoft YaHei', Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif;\n" +
            "        font-size: 16px;\n" +
            "        line-height: 1em;\n" +
            "        padding: 1em;\n" +
            "        margin: auto;\n" +
            "        /*max-width:80%;*/\n" +
            "        background: #fefefe;\n" +
            "        text-align: left;\n" +
            "    }\n" +
            "\n" +
            "    #content h1, h2, h3, h4, h5, h6 {\n" +
            "        font-weight: bold;\n" +
            "    }\n" +
            "\n" +
            "    #content h1 {\n" +
            "        color: #000000;\n" +
            "        font-size: 28px;\n" +
            "    }\n" +
            "\n" +
            "    #content h2 {\n" +
            "        border-bottom: 2px solid #CCCCCC;\n" +
            "        color: #000000;\n" +
            "        font-size: 24px;\n" +
            "        padding-bottom: 5px;\n" +
            "    }\n" +
            "\n" +
            "    #content h3 {\n" +
            "        border-bottom: 1px solid #CCCCCC;\n" +
            "        font-size: 18px;\n" +
            "        padding-bottom: 2px;\n" +
            "    }\n" +
            "\n" +
            "    #content h4 {\n" +
            "        font-size: 16px;\n" +
            "    }\n" +
            "\n" +
            "    #content h5 {\n" +
            "        font-size: 14px;\n" +
            "    }\n" +
            "\n" +
            "    #content h6 {\n" +
            "        color: #777777;\n" +
            "        background-color: inherit;\n" +
            "        font-size: 14px;\n" +
            "    }\n" +
            "\n" +
            "    #content hr {\n" +
            "        height: 0.2em;\n" +
            "        border: 0;\n" +
            "        color: #CCCCCC;\n" +
            "        background-color: #CCCCCC;\n" +
            "    }\n" +
            "\n" +
            "    #content p, blockquote, ul, ol, dl, li, #content table, pre {\n" +
            "        margin: 15px 0;\n" +
            "    }\n" +
            "\n" +
            "    #content p {\n" +
            "        margin: 1em 0;\n" +
            "    }\n" +
            "\n" +
            "    #content pre {\n" +
            "        background-color: #F8F8F8;\n" +
            "        border: 1px solid #CCCCCC;\n" +
            "        border-radius: 3px;\n" +
            "        overflow: auto;\n" +
            "        padding: 5px;\n" +
            "    }\n" +
            "\n" +
            "    #content pre code {\n" +
            "        background-color: #F8F8F8;\n" +
            "        border: none;\n" +
            "        padding: 0;\n" +
            "    }\n" +
            "\n" +
            "    #content code {\n" +
            "        font-family: Consolas, Monaco, Andale Mono, monospace;\n" +
            "        background-color: #F8F8F8;\n" +
            "        border: 1px solid #CCCCCC;\n" +
            "        border-radius: 3px;\n" +
            "        padding: 0 0.2em;\n" +
            "        line-height: 1;\n" +
            "        line-height: 1.5;\n" +
            "        font-size: 13px;\n" +
            "    }\n" +
            "\n" +
            "    #content pre > code {\n" +
            "        border: 0;\n" +
            "        margin: 0;\n" +
            "        padding: 0;\n" +
            "    }\n" +
            "\n" +
            "    #content a {\n" +
            "        color: #0645ad;\n" +
            "        text-decoration: none;\n" +
            "    }\n" +
            "\n" +
            "    #content a:visited {\n" +
            "        color: #0b0080;\n" +
            "    }\n" +
            "\n" +
            "    #content a:hover {\n" +
            "        color: #06e;\n" +
            "    }\n" +
            "\n" +
            "    #content a:active {\n" +
            "        color: #faa700;\n" +
            "    }\n" +
            "\n" +
            "    #content a:focus {\n" +
            "        outline: thin dotted;\n" +
            "    }\n" +
            "\n" +
            "    #content a:hover, a:active {\n" +
            "        outline: 0;\n" +
            "    }\n" +
            "\n" +
            "    #content ::-moz-selection {\n" +
            "        background: rgba(255, 255, 0, 0.3);\n" +
            "        color: #000\n" +
            "    }\n" +
            "\n" +
            "    #content ::selection {\n" +
            "        background: rgba(255, 255, 0, 0.3);\n" +
            "        color: #000\n" +
            "    }\n" +
            "\n" +
            "    #content a::-moz-selection {\n" +
            "        background: rgba(255, 255, 0, 0.3);\n" +
            "        color: #0645ad\n" +
            "    }\n" +
            "\n" +
            "    #content a::selection {\n" +
            "        background: rgba(255, 255, 0, 0.3);\n" +
            "        color: #0645ad\n" +
            "    }\n" +
            "\n" +
            "    #content blockquote {\n" +
            "        color: #666666;\n" +
            "        margin: 0;\n" +
            "        padding-left: 2em;\n" +
            "        border-left: 0.5em #EEE solid;\n" +
            "    }\n" +
            "\n" +
            "    #content ul li{\n" +
            "        list-style-type: disc;\n" +
            "    }\n" +
            "\n" +
            "    #content ol li{\n" +
            "        list-style-type: decimal;\n" +
            "    }\n" +
            "\n" +
            "    #content ul, ol {\n" +
            "        margin: 1em 0;\n" +
            "        padding: 0 0 0 2em;\n" +
            "    }\n" +
            "\n" +
            "    #content li p:last-child {\n" +
            "        margin: 0\n" +
            "    }\n" +
            "\n" +
            "    #content dd {\n" +
            "        margin: 0 0 0 2em;\n" +
            "    }\n" +
            "\n" +
            "    #content img {\n" +
            "        border: 0;\n" +
            "        -ms-interpolation-mode: bicubic;\n" +
            "        vertical-align: middle;\n" +
            "        max-width: 100%;\n" +
            "    }\n" +
            "\n" +
            "    #content table {\n" +
            "        border-collapse: collapse;\n" +
            "        border-spacing: 0;\n" +
            "    }\n" +
            "\n" +
            "    #content td {\n" +
            "        vertical-align: top;\n" +
            "    }\n" +
            "\n" +
            "    #content\n" +
            "\n" +
            "    @media only screen and (min-width: 480px) {\n" +
            "        body {\n" +
            "            font-size: 14px;\n" +
            "        }\n" +
            "    }\n" +
            "\n" +
            "    #content\n" +
            "\n" +
            "    @media only screen and (min-width: 768px) {\n" +
            "        body {\n" +
            "            font-size: 16px;\n" +
            "        }\n" +
            "    }\n" +
            "    table.gridtable {\n" +
            "        font-family: verdana,arial,sans-serif;\n" +
            "        font-size:11px;\n" +
            "        color:#333333;\n" +
            "        border-width: 1px;\n" +
            "        border-color: #666666;\n" +
            "        border-collapse: collapse;\n" +
            "    }\n" +
            "    table.gridtable th {\n" +
            "        border-width: 1px;\n" +
            "        padding: 8px;\n" +
            "        border-style: solid;\n" +
            "        border-color: #666666;\n" +
            "        background-color: #dedede;\n" +
            "    }\n" +
            "    table.gridtable td {\n" +
            "        border-width: 1px;\n" +
            "        padding: 8px;\n" +
            "        border-style: solid;\n" +
            "        border-color: #666666;\n" +
            "        background-color: #ffffff;\n" +
            "    }\n" +
            "\n" +
            "    table.imagetable {\n" +
            "        font-family: verdana,arial,sans-serif;\n" +
            "        font-size:11px;\n" +
            "        color:#333333;\n" +
            "        border-width: 1px;\n" +
            "        border-color: #999999;\n" +
            "        border-collapse: collapse;\n" +
            "    }\n" +
            "    table.imagetable th {\n" +
            "        background:#b5cfd2 url('/js/ibnms/cccp/sitablecss/cell-blue.jpg');\n" +
            "        border-width: 1px;\n" +
            "        padding: 8px;\n" +
            "        border-style: solid;\n" +
            "        border-color: #999999;\n" +
            "    }\n" +
            "    table.imagetable td {\n" +
            "        background:#dcddc0 url('/js/ibnms/cccp/sitablecss/cell-grey.jpg');\n" +
            "        border-width: 1px;\n" +
            "        padding: 8px;\n" +
            "        border-style: solid;\n" +
            "        border-color: #999999;\n" +
            "    }\n";
}
